package com.dsx.dsms.controller;

import com.alibaba.fastjson.JSONObject;
import com.dsx.dsms.pojo.Article;
import com.dsx.dsms.pojo.Student;
import com.dsx.dsms.pojo.User;
import com.dsx.dsms.service.ArticleService;
import com.dsx.dsms.service.CoachService;
import com.dsx.dsms.service.StudentService;
import com.dsx.dsms.service.UserService;
import com.dsx.dsms.util.Page;
import com.dsx.dsms.util.Transform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

/**
 * @author dsx
 */
@Controller
@RequestMapping("")
public class ForeController {
    @Autowired
    UserService userService;
    @Autowired
    ArticleService articleService;
    @Autowired
    CoachService coachService;
    @Autowired
    StudentService studentService;

    @ResponseBody
    @RequestMapping("fore_login")
    public String login(String username, String password,int type,
                        HttpSession session) {
        User user = userService.getUserByType(username,password,type);
        JSONObject jsonObject = new JSONObject();
        System.out.println(user);

        if(user == null){
            jsonObject.put("flag",-1);
        }
        else{
            switch(type){
                case 1:
                    session.setAttribute("coach",user);
                    System.out.println("coach");
                    break;
                case 2:
                    session.setAttribute("student",user);
                    System.out.println("student");
                    break;
                default :
                    session.setAttribute("admin",user);
                    System.out.println("admin");
            }
            jsonObject.put("flag",type);
            jsonObject.put("user",user);
        }
        return jsonObject.toJSONString();
    }


    @ResponseBody
    @RequestMapping("fore_student_index")
    public String getUser(HttpSession session) {
        User user = (User) session.getAttribute("student");
        Page page = new Page();
        page.setCount(100);
        List<Article> articleList = articleService.list(page);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", user);
        jsonObject.put("as",articleList);
        return jsonObject.toJSONString();
    }

    @ResponseBody
    @RequestMapping("fore_student_register")
    public String register(String username, String password, String name,
                           String phone, MultipartFile pic, String sex,
                           String locate, String carModel,
                           HttpServletRequest request) {

        username = HtmlUtils.htmlEscape(username);
        int flag = userService.getUserByUserName(username);
        JSONObject jsonObject = new JSONObject();
        if(flag == 1){
            //用户名已存在
            jsonObject.put("flag", -1);
            return jsonObject.toJSONString();
        }
        if(pic.isEmpty()){
            //文件为空   flag = 0
            jsonObject.put("flag", 0);
            return jsonObject.toJSONString();
        }
        // 用户名太长
        if(username.length()>20){
            jsonObject.put("flag", 20);
            return jsonObject.toJSONString();
        }
        String[] arr = pic.getOriginalFilename().split("\\.");
        String picName = Transform.getRandomFileName() + "." + arr[1];
        System.out.println("picName------> " + picName);
        Student student = new Student();
        student.setName(name);
        student.setTelephone(phone);
        student.setAddress(locate);
        student.setCarModel(carModel);
        userService.insertStudent(student);
        int id = student.getId();
        userService.insertUser(username,password,id, sex, picName,2);
        String path = request.getServletContext().getRealPath("/img/student/");
        try{
            File file = new File(path + File.separator + picName);
            System.out.println("file------>  " + file);
            pic.transferTo(file);
        }catch (Exception e){
            //文件保存失败   flag = 2
            jsonObject.put("flag", 2);
            return jsonObject.toJSONString();
        }

        //注册成功   flag = 1
        jsonObject.put("flag", 1);
        return jsonObject.toJSONString();
    }
    @ResponseBody
    @RequestMapping("fore_student_article")
    public String getArticle(int id){
        JSONObject jsonObject = new JSONObject();
        Article article = articleService.getArticleById(id);
        jsonObject.put("article", article);
        return jsonObject.toJSONString();
    }
    @ResponseBody
    @RequestMapping("fore_student_updateUser")
    public String updateUser(HttpSession httpSession){
        User user = (User) httpSession.getAttribute("student");
        int time2 = coachService.totalTime(user.getStudent().getId(), user.getStudent().getSubject2());
        int time3 = coachService.totalTime(user.getStudent().getId(), user.getStudent().getSubject3());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", user);
        jsonObject.put("time2", time2);
        jsonObject.put("time3", time3);
        return jsonObject.toJSONString();
    }


    @RequestMapping("fore_student_reset")
    public String userReset(String name, String password, String telephone,
                            MultipartFile pic, String address, String identity,
                           String sex, HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute("student");
        if(pic.getSize() != 0){
            String[] arr = pic.getOriginalFilename().split("\\.");
            String picName = Transform.getRandomFileName() + "." + arr[1];
            user.setPic(picName);
            String path = request.getServletContext().getRealPath("/img/student/");
            try{
                File file = new File(path + File.separator + picName);
                pic.transferTo(file);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        user.setPassword(password);
        user.setSex(sex);
        userService.upload(user);
        Student student = user.getStudent();
        student.setName(name);
        student.setAddress(address);
        student.setIdentity(identity);
        student.setTelephone(telephone);
        studentService.update(student);

        return "redirect:upperson.html";

    }


}
